const {
  setTimeout,
  setInterval,
  clearTimeout,
  clearInterval,
} = require("timers");

let config = [
  ["输入牌子或者用户名字", "输入语音内容"],
  ["为主播点赞了", "有人点赞主播"]
];

function base64Decode(base64Str) {
  // 将 URL 安全的 Base64 编码字符串转换为标准 Base64 编码字符串
  const base64 = base64Str.replace(/-/g, "+").replace(/_/g, "/");

  // 补齐缺少的尾部填充字符
  const padding = base64.length % 4;
  if (padding === 2) {
    base64 += "==";
  } else if (padding === 3) {
    base64 += "=";
  }

  // 解码 Base64 编码字符串
  const decodedData = atob(base64);

  // 将解码后的字符串转换为 UTF-8 编码的文本
  const decoder = new TextDecoder("utf-8");
  const decodedString = decoder.decode(
    new Uint8Array([...decodedData].map((char) => char.charCodeAt(0)))
  );

  return decodedString;
}

function speckText(text) {
  var speechInstance = new window.SpeechSynthesisUtterance(text);
  speechInstance.lang = "zh";
  speechInstance.volume = 100; // 音量
  speechInstance.rate = 0.7; // 语速, 默认值是1, 范围是0.1到10
  speechInstance.pitch = 1.5; // 音高, 默认值是1, 范围是0到2
  window.speechSynthesis.speak(speechInstance);
}

let readyinterval = setInterval(() => {
  console.log("等待加载");

  if (document.getElementById("jsonFileElement")) {
    clearInterval(readyinterval);
    console.log("加载完成");

    let jsonFileElement = document.getElementById("jsonFileElement");
    let jsonData = JSON.parse(base64Decode(jsonFileElement.textContent));
    config = jsonData.config;
    console.log(config);

    // 停止播放直播画面
    var stopVideointerval = setInterval(() => {
      document.querySelectorAll("video").forEach(function (video) {
        video.pause();
        video.volume = 0.01;
      });
    }, 500);
    setTimeout(function () {
      clearInterval(stopVideointerval);
    }, 60000);

    // 查看进入直播间的b站用户
    const brush_prompt = document.querySelector(".brush-prompt");
    let prevText = brush_prompt.textContent;

    setInterval(() => {
      const currText = brush_prompt.textContent;
      if (currText !== prevText) {
        config.forEach((item) => {
          if (currText.includes(item[0])) {
            speckText(item[1]);
          }
        });
        // console.log(currText);
        prevText = currText;
      }
    }, 500);
  }
}, 200);
